package com.designpattern.MediatorPattern;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author yue
 * @Date 2021-07-26
 * @Version V1.0.1
 * @Description 中介者抽象类
 */

public abstract class Mediator {

    //注册同事
    abstract void register(Colleague colleague);

    //通知中介者，发送消息
    abstract void relay(Colleague colleague);


}

/**
 * 具体中介者实现类
 */
class ConcreteMediator extends Mediator{


    /**
     * 被中介者代理的同事
     */
    private List<Colleague> colleagues;

    public ConcreteMediator() {
        colleagues = new ArrayList<Colleague>();
    }


    @Override
    void register(Colleague colleague) {
        if (!colleagues.contains(colleague)) {
            colleague.setMediator(this);
            this.colleagues.add(colleague);
        }
    }

    @Override
    void relay(Colleague colleague) {
        colleagues.forEach(c -> {
            if (!c.equals(colleague)) {
                c.receive();
            }
        });
    }

}